import React, { useEffect, useState } from "react"
import {Breadcrumb,Badge,Menu,Dropdown,Button,Form,notification}  from 'antd'
import {
  MenuFoldOutlined,MenuUnfoldOutlined,ReloadOutlined,BellOutlined
} from '@ant-design/icons';
import { withRouter } from "react-router-dom";
import { connect } from 'react-redux'
import { tabOpenOrClose,clearHistoryRouter,checkPublishData,checkDraftData,addHistoryRouter,removeUserInfo } from 'redux/action'
import LlxModal from 'components/LlxModal/index'
import LlxForm from 'components/LlxForm/index'
import classNames from "classnames";
import {editUserPassword} from 'api/index'
function HeaderItem(props){
  // 数据
  const {menus,collapsed} = props
  const [contents,isDanger,isDisabled,width] = ['',false,false,600]
  const modalData = {contents,isDanger,isDisabled,width}
  const [form] = Form.useForm();
  const formItemUser = [
    {label: '旧密码',type:'input',rules:[
      {
        required: true,
        message: '请输入旧密码',
      },
    ],name: 'oldPassword', id:1 , span: 20 },
    {label: '新密码',type:'input',rules:[
      {
        required: true,
        message: '请输入新密码',
      },
    ], name: 'password', id:3 , span: 20 }
  ]
   // 其他
   const FormComponent = () => {
    return  <LlxForm labelCol={8} form={form} formItem={formItemUser}/>
  }



// 获取面包屑导航
const [breadcrumbList,setBreadcrumbList] = useState([])
useEffect(()=>{
  // 获取面包屑数据
  const data = props.location.pathname.split('/').filter(i=>i)
  if(data[2]){
    setBreadcrumbList(()=>[menus.filter(i=>i.url===data[1])[0],menus.filter(i=>i.url===data[1])[0].children.filter(i=>i.url===data[2])[0]])
  } else  {
    setBreadcrumbList(()=>[menus.filter(i=>i.url===data[1])[0]])
  }
},[menus, props])

// 1.伸缩侧边栏
const setCollapsed = ()=>{
  props.tabOpenOrCloseFn()
}

// 2.退出登录
 const userOut =()=>{
     const baseUrl = window.location.href.indexOf('/prd')
    baseUrl === -1 ?localStorage.removeItem('token-llx-test'):localStorage.removeItem('token-llx')
  // 如果本地有token, 就带着
    props.clearHistoryRoute()
    props.removeUserInfo()
    props.history.push('/login')
  }

// 3.确认弹框
const handleOk = (props) => {
  form.validateFields().then(async()=>{  

   const res = await editUserPassword({
      id: form.getFieldValue().id,
      oldPassword: form.getFieldValue().oldPassword,
      password: form.getFieldValue().password
    })
    notification.success({
     message: res.message,
    duration:1
     });
  })
  }
  // 4.是否是编辑按钮
const isEdit = () => {
  form.setFieldsValue({
    id:props.userInfo.user.id
  })
      return new Promise((resolve, reject) => {
        // 模拟获取表单数据
          resolve()
      });
   }
  //  5.刷新页面
  const updatePage = () => {
    window.location.reload()
  }
  // 6.去任务页
  const goTaskPaper = () => {
    props.history.push('/view/ordinary/task')
   props.addRouter({
  menuName:'任务分配',url:'ordinary/task' 
})
  }
  const showHistory = [
    'wordLibrary',
    'wordInfo',
    'videoLibrary',
    'themeSubjectInfo',
    'planLibrary',
    'videoInfo',
    'videoAlbumLibrary',
    'videoAlbumInfo',
    'testPaperLibrary',
    'testPaperInfo',
    'bookLibrary',
    'intensiveBook',
    'intensiveBookInfo',
    'bookInfo',
    'bookInfoInten',
    'audioLibrary',
    'audioInfo',
    'courseSubject',
    'studyVideoLibrary',
    'studyInfo'
  ]


  return <>
  {
    collapsed?<MenuFoldOutlined className='icon' onClick={()=>setCollapsed(i=>!i)}/>:<MenuUnfoldOutlined className='icon' onClick={()=>setCollapsed(i=>!i)}/>
   }

    <ReloadOutlined onClick={updatePage} className='icon' style={{marginLeft:'10px'}}/>


    <Breadcrumb>

    {breadcrumbList.map(i=>{
      return <Breadcrumb.Item key={i.menuName}>{i.menuName}</Breadcrumb.Item>
    })}
 </Breadcrumb>

  <div className="data-status">
     <span className="breadBtn test">测试版本</span>
     {
       showHistory.includes(props.location.pathname.split('/').filter(i=>i)[2])?<>
        <span onClick={props.checkDraftDataBtn} className={classNames(props.examineStatus?'breadBtn':'active breadBtn')}>草稿</span>
       <span onClick={props.checkPublishDataBtn} className={classNames(props.examineStatus?'active breadBtn':'breadBtn')}>发布</span>
       </>:''
     }
    
  </div>
 <div className="user">

     <Badge count={props.taskCount} offset={[0,10]}>
      <BellOutlined className="head-icon" onClick={goTaskPaper}/>
    </Badge>

      <Dropdown overlay={<Menu
    items={props.userInfo.roles.map(i => i.id).includes(101)?[
      {
        label: (
         <a className="text-link" href="http://139.224.81.105/test_app/#/login">&nbsp;&nbsp;运营中台</a>
        ),
      },
      {
        label: (
          <LlxModal btnText={'更改密码'} title={'更改密码'} link={true} form={form} isEdit={()=>isEdit()} {...modalData} handleOk={handleOk} FormComponent={FormComponent}></LlxModal>
        ),
      },
      {
        label: (
          <div className="text-color-red" style={{marginLeft:'25px',width:'100%'}} onClick={userOut}>
            退出
          </div>
        ),
      }
    ]:[
      {
        label: (
          <LlxModal btnText={'更改密码'} title={'更改密码'} link={true} form={form} isEdit={()=>isEdit()} {...modalData} handleOk={handleOk} FormComponent={FormComponent}></LlxModal>
        ),
      },
      {
        label: (
          <div className="text-color-red" style={{marginLeft:'25px',width:'100%'}} onClick={userOut}>
            退出
          </div>
        ),
      }
    ]}
  />} placement="bottom">
        <Button type="link">{props.userInfo.user.userName}</Button>
      </Dropdown>
    

   
   
 </div>


 
 </>
}

// 映射数据
const mapStateToProps = (state) => {
  return {
    menus:state.menus,
    collapsed:state.collapsed,
    examineStatus:state.examineStatus,
    userInfo:state.userInfo,
    taskCount:state.taskCount
  }
}

// 映射方法
const mapDispatchToProps = (dispatch) => {
  return {
    addRouter: (route) => dispatch(addHistoryRouter(route)),
    tabOpenOrCloseFn: () => dispatch(tabOpenOrClose()),
    clearHistoryRoute: () => dispatch(clearHistoryRouter()),
    checkPublishDataBtn: () => dispatch(checkPublishData()),
    checkDraftDataBtn: () => dispatch(checkDraftData()),
    removeUserInfo: () => dispatch(removeUserInfo())
  }
}
 export default withRouter(connect(mapStateToProps, mapDispatchToProps)(HeaderItem))
